package com.meteor.framework.mybatis.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meteor.framework.common.constant.Constant;
import com.meteor.framework.common.enums.DataScopeEnum;
import com.meteor.framework.common.exception.ServerException;
import com.meteor.framework.common.query.Query;
import com.meteor.framework.mybatis.interceptor.DataScope;
import com.meteor.framework.mybatis.service.BaseService;
import com.meteor.framework.security.user.SecurityUser;
import com.meteor.framework.security.user.UserDetail;

import java.util.List;
import java.util.Map;


/**
 * 基础服务类，所有Service都要继承
 *
 * @author lynn
 * @date 2024/1/03
 */
public class BaseServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements BaseService<T> {

    /**
     * 获取分页对象
     *
     * @param query 分页参数
     */
    protected IPage<T> getPage(Query query) {
        Page<T> page = new Page<>(query.getPage(), query.getLimit());

        // 排序
        if (StringUtils.isNotBlank(query.getOrder())) {
            if (query.isAsc()) {
                return page.addOrder(OrderItem.asc(query.getOrder()));
            } else {
                return page.addOrder(OrderItem.desc(query.getOrder()));
            }
        }

        return page;
    }

    /**
     * MyBatis-Plus 数据权限
     */
    protected void dataScopeWrapper(LambdaQueryWrapper<T> queryWrapper) {
        DataScope dataScope = getDataScope(null, null,null);
        if (dataScope != null) {
            queryWrapper.apply(dataScope.getSqlFilter());
        }
    }

    /**
     * 原生SQL 数据权限
     *
     * @param tableAlias 表别名，多表关联时，需要填写表别名
     * @param orgIdAlias 机构ID别名，null：表示org_id
     * @return 返回数据权限
     */
    protected DataScope getDataScope(String tableAlias, String orgIdAlias,String table) {
        UserDetail user = SecurityUser.getUser();
        if(user == null){
            throw new ServerException("无权限！");
        }
        // 如果是超级管理员，则不进行数据过滤
        if (user.getSuperAdmin().equals(Constant.SUPER_ADMIN)) {
            return null;
        }

        // 如果为null，则设置成空字符串
        if (tableAlias == null) {
            tableAlias = "";
        }

        // 获取表的别名
        if (StringUtils.isNotBlank(tableAlias)) {
            tableAlias += ".";
        }

        StringBuilder sqlFilter = new StringBuilder();
        sqlFilter.append(" (");

        // 数据权限范围
        List<String> dataScopeList = user.getDataScopeList();
        // 全部数据权限
        if (dataScopeList == null) {
            return null;
        }
        // 数据过滤
        if (dataScopeList.size() > 0) {
            if (StringUtils.isBlank(orgIdAlias)) {
                orgIdAlias = "org_id";
            }
            sqlFilter.append(tableAlias).append(orgIdAlias);

            sqlFilter.append(" in(\"").append(StrUtil.join("\",\"", dataScopeList)).append("\")");

            sqlFilter.append(" or ");

            if((!ObjectUtils.isEmpty(table)||table==null)&&(!ObjectUtils.isEmpty(table)&&!table.equals("sys_org"))) {

                orgIdAlias = "community_id";

                sqlFilter.append(tableAlias).append(orgIdAlias);

                sqlFilter.append(" in(\"").append(StrUtil.join("\",\"", dataScopeList)).append("\")");

                sqlFilter.append(" or ");
            }

        }

        // 查询本人数据
        sqlFilter.append(tableAlias).append("created_by").append("=").append("\"").append(user.getId()).append("\"");
//        sqlFilter.append(tableAlias).append("created_by").append("=");

        sqlFilter.append(")");

        return new DataScope(sqlFilter.toString());
    }

    protected DataScope getDataScope1(String tableAlias, String orgIdAlias,String table) {
        UserDetail user = SecurityUser.getUser();
        if(user == null){
            throw new ServerException("无权限！");
        }
        // 如果是超级管理员，则不进行数据过滤
        if (user.getSuperAdmin().equals(Constant.SUPER_ADMIN)) {
            return null;
        }

        // 如果为null，则设置成空字符串
        if (tableAlias == null) {
            tableAlias = "";
        }

        // 获取表的别名
        if (StringUtils.isNotBlank(tableAlias)) {
            tableAlias += ".";
        }

        StringBuilder sqlFilter = new StringBuilder();
        sqlFilter.append(" (");

        // 数据权限范围
//        List<String> dataScopeList = user.getDataScopeList();
        Map<String, List<String>> dataScopeMap = user.getDataScopeMap();
        // 全部数据权限
        if (dataScopeMap == null) {
            return null;
        }
        // 数据过滤

        if(dataScopeMap!=null&&!ObjectUtils.isEmpty(dataScopeMap.get(DataScopeEnum.ORG_AND_CHILD.getValue().toString()))&&dataScopeMap.get(DataScopeEnum.ORG_AND_CHILD.getValue().toString()).size()>0){
            List<String> dataScopeList = dataScopeMap.get(DataScopeEnum.ORG_AND_CHILD.getValue().toString());
            if (StringUtils.isBlank(orgIdAlias)) {
                orgIdAlias = "org_id";
            }
            sqlFilter.append(tableAlias).append(orgIdAlias);

            sqlFilter.append(" in(\"").append(StrUtil.join("\",\"", dataScopeList)).append("\")");

            sqlFilter.append(" or ");
        }else if(dataScopeMap!=null&&!ObjectUtils.isEmpty(dataScopeMap.get(DataScopeEnum.COMMUNITY.getValue().toString()))&&dataScopeMap.get(DataScopeEnum.COMMUNITY.getValue().toString()).size()>0){
            List<String> dataScopeList = dataScopeMap.get(DataScopeEnum.COMMUNITY.getValue().toString());

            if(!ObjectUtils.isEmpty(table)&&table.equals("sys_org")){
                if (StringUtils.isBlank(orgIdAlias)) {
                    orgIdAlias = "org_id";
                }
                sqlFilter.append(tableAlias).append(orgIdAlias);

                dataScopeList.add(user.getOrgId());
                sqlFilter.append(" in(\"").append(StrUtil.join("\",\"", dataScopeList)).append("\")");
                sqlFilter.append(" or ");
            }else if(!table.equals("pf_community")) {
                orgIdAlias = "community_id";

                sqlFilter.append(tableAlias).append(orgIdAlias);

                sqlFilter.append(" in(\"").append(StrUtil.join("\",\"", dataScopeList)).append("\")");
                sqlFilter.append(" or ");
            }else{
                orgIdAlias = "id";

                sqlFilter.append(tableAlias).append(orgIdAlias);

                sqlFilter.append(" in(\"").append(StrUtil.join("\",\"", dataScopeList)).append("\")");
                sqlFilter.append(" or ");
            }
        }else if(dataScopeMap!=null&&!ObjectUtils.isEmpty(dataScopeMap.get(DataScopeEnum.ORG_ONLY.getValue().toString()))&&dataScopeMap.get(DataScopeEnum.ORG_ONLY.getValue().toString()).size()>0){
            List<String> dataScopeList = dataScopeMap.get(DataScopeEnum.ORG_ONLY.getValue().toString());
            if (StringUtils.isBlank(orgIdAlias)) {
                orgIdAlias = "org_id";
            }
            sqlFilter.append(tableAlias).append(orgIdAlias);

            sqlFilter.append(" in(\"").append(StrUtil.join("\",\"", dataScopeList)).append("\")");
            sqlFilter.append(" or ");
        }

        // 查询本人数据
        sqlFilter.append(tableAlias).append("created_by").append("=").append("\"").append(user.getId()).append("\"");
//        sqlFilter.append(tableAlias).append("created_by").append("=");

        sqlFilter.append(")");

        return new DataScope(sqlFilter.toString());
    }
}